package zero;

import io.netty.buffer.Unpooled;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 基于NIO的数据传输 零拷贝数据传输
 * @author yunlongn
 */
public class NettyServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ServerSocket serverSocket = serverSocketChannel.socket();

        serverSocket.setReuseAddress(true);

        serverSocket.bind(new InetSocketAddress(8899));


        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
        while (true){
            Unpooled.buffer(10);
            SocketChannel socketChannel = serverSocketChannel.accept();
            String outPath = "D:\\out";
            FileChannel fileChannel = new FileOutputStream(outPath).getChannel();
            socketChannel.configureBlocking(true);
            int readCount = 0;
            while (-1 < readCount) {
                try {
                    readCount = socketChannel.read(byteBuffer);
                }catch (Exception e) {
                    readCount = -1;
                    e.printStackTrace();
                }
                byteBuffer.flip();
                fileChannel.write(byteBuffer);
                byteBuffer.clear();
            }
            fileChannel.close();

        }
    }
}
